/*出口加工贸易中当备案号为B开头后加11位数字以及监管方式为来料加工时工缴费显示*/
function isVisibility() {
    if ($.fn.order.isExport) {
        if ($.fn.order.isProcessTrade) {
            var recordId = $("input[name='record_id']").val();
            var tradeModeCode = $("input[name='trade_mode_code']").val();
            if (/^B[0-9]{11}$/.test(recordId) && tradeModeCode == '0214') {
                $("#processing_fee").parent().show();
                $("#processing_fee").parent().prev().show();
                //如果采用新版设计的话，下面这句话必须屏蔽
                $("#goods_no").parent().removeClass("five").addClass("two");
                //启用下面这句话
                /*$("#packinglist_remark").parent().removeClass("three").addClass("four");*/
            } else {
                $("#processing_fee").parent().hide();
                $("#processing_fee").parent().prev().hide();
                //如果采用新版设计的话，下面这句话必须屏蔽
                $("#goods_no").parent().removeClass("two").addClass("five");
                //启用下面这句话
                /*$("#packinglist_remark").parent().removeClass("four").addClass("three");*/
            }
        }
    }
}

/*当存在关联关系时触发表单验证*/
function relateValidate(form, fields) {
    var $form;
    var $field
    var reg = /^[#\.][aA-zZ]+$/;
    if ($("#" + form).length) {
        $form = $("#" + form);
    } else if ($("." + form).length) {
        $form = $("." + form);
    }
    var gets = $form.form("get");
    var valids = $form.form("validate");
    for (var i = 0; i < fields.length; i++) {
        if (reg.test(fields[i])) {
            $field = $(fields[i]);
        } else {
            $field = $("input[name='" + fields[i] + "']");
        }
        var validationRules = gets.validation($field);
        valids.field(validationRules);
    }
}

//添加申报口岸，包装种类其他，其他货源地的值到备注中
var detailsPack;

function addRemark(arg) {
    var rk =  $("input[name='remark']");
    var rkInitFlag = rk.attr("init");
    if(rk.attr("stopAutoComp")){
        return;
    }
    if(rkInitFlag !== "done"){
        return;
    }
    rk.val(combineRemark(arg));
}

function combineRemark(arg){
    var remark = '';
    var defaultRemark = $.fn.order.isExport ? "结汇,退税" : "付汇";
    var declaration_port = $("input[name='declaration_port']").val();
    var otherGoodsAddr = $("input[name='other_goods_addr']").val();
    if (declaration_port != ' ' && declaration_port) {
        remark += declaration_port + ",";
        if (declaration_port == '三水港') {
            defaultRemark = $.fn.order.isExport ? "收汇,退税" : "付汇";
        }
    }
    remark += defaultRemark;
    if ($.fn.order.isTongguanYth == '1' && $.fn.order.isExport) {
        var export_port = $("input[name='export_port']").val();
        var export_port_code = $("input[name='export_port_code']").val();
        remark += ";通关一体化";
        if (export_port && export_port_code) {
            remark += ",实际出口口岸：" + export_port + "，代码：" + export_port_code;
        }
    }
    if (arg != ' ' && arg) {
        remark += "," + arg;
    }
    if (otherGoodsAddr != ' ' && otherGoodsAddr) {
        remark += ",其他货源地：" + otherGoodsAddr;
    }
    return remark;
}

/**
 * 获取报关供应商信息,报关费用详细说明
 */
function getDetailsInfo() {
    var customBrokerInfoTable = "<table class=\"custom-broker-info\">" +
                                "<tbody>" +
                                "<tr>" +
                                "<td class=\"custom-label\">报关行：</td>" +
                                "<td class=\"custom-content custom-company\"><!--佛山市佛港报关有限公司--></td>"
                                +
                                "<td class=\"custom-label\">海关注册代码：</td>" +
                                "<td class=\"custom-content custom-register-code\"><!--4406980023--></td>"
                                +
                                "</tr>" +
                                "<tr>" +
                                "<td class=\"custom-label\">联系人：</td>" +
                                "<td class=\"custom-content custom-contacts\"><!--陈小姐--></td>"
                                +
                                "<td class=\"custom-label\">&nbsp;</td>" +
                                "<td class=\"custom-content\">&nbsp;</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td class=\"custom-label\">电话：</td>" +
                                "<td class=\"custom-content custom-tel\"><!--83312144--></td>"
                                +
                                "<td class=\"custom-label\">手机：</td>" +
                                "<td class=\"custom-content custom-phone\"><!--83312144--></td>"
                                +
                                "</tr>" +
                                "</tbody>" +
                                "</table>";
    var detailsInfoFeeTable = "<table class='details-info-fee'>" +
                              "<thead>" +
                              "<tr>" +
                              "<td class='fee-column-name'>费用名称</td>" +
                              "<td>描述</td>" +
                              /*"<td>箱型</td>" +*/
                              "<td class='fee-column-name'>数量</td>" +
                              "<td class='fee-column-name'>单价</td>" +
                              "<td class='fee-column-name'>金额</td>" +
                              "</tr>" +
                              "<tr>" +
                              "<td class='fee-column-name'>&nbsp;</td>" +
                              "<td>&nbsp;</td>" +
                              /* "<td>&nbsp;</td>" +*/
                              "<td class='fee-column-name'>&nbsp;</td>" +
                              "<td class='fee-column-name'>RMB</td>" +
                              "<td class='fee-column-name'>RMB</td>" +
                              "</tr>" +
                              "</thead>" +
                              "<tbody>" +
                              "</tbody>" +
                              "<tfoot>" +
                              "<tr>" +
                              "<td>&nbsp;</td >" +
                              "<td>&nbsp;</td>" +
                              /*"<td>&nbsp;</td>" +*/
                              "<td >&nbsp;</td>" +
                              "<td >合计</td>" +
                              "<td class=\"all-total\"></td>" +
                              "</tr>" +
                              "</tfoot>" +
                              "</table>";
    var warnTipsStr = "<div class='extract-tips'>说明：最终价格以提交时的报价清单为准。</div>";
    var detailsInfoTableStr = "<div class='details-info-container' STYLE='max-height:600px;'>"
                              + customBrokerInfoTable
                              + detailsInfoFeeTable + warnTipsStr +
                              "</div>";
    var openIndex = layer.open({
                                   type: 1,
                                   area: '700px',
                                   offset: '100px',
                                   shadeClose: true,
                                   skin: 'yourclass',
                                   content: detailsInfoTableStr
                               });
    $(".details-info-container").find(".custom-company")
        .text(requestSupCompniesInfo.initSupCompaniesData.data.supInfo.comName).end()
        .find(".custom-register-code")
        .text(requestSupCompniesInfo.initSupCompaniesData.data.supInfo.comCode)
        .end().find(".custom-contacts")
        .text(requestSupCompniesInfo.initSupCompaniesData.data.supInfo.contactor).end()
        .find(".custom-tel")
        .text(requestSupCompniesInfo.initSupCompaniesData.data.supInfo.tel).end()
        .find(".custom-phone")
        .text(requestSupCompniesInfo.initSupCompaniesData.data.supInfo.phone);
    if (requestSupCompniesInfo.initSupCompaniesData.data.charging.length) {
        for (var i = 0; i < requestSupCompniesInfo.initSupCompaniesData.data.charging.length; i++) {
            var descript = requestSupCompniesInfo.initSupCompaniesData.data.charging[i].descript;
            descript = !descript ? '' : descript;
            $(".details-info-container").find(".details-info-fee").find("tbody").append("<tr>"
                                                                                        +
                                                                                        "<td>"
                                                                                        + requestSupCompniesInfo.initSupCompaniesData.data.charging[i].name
                                                                                        + "</td>"
                                                                                        +
                                                                                        "<td>"
                                                                                        + descript
                                                                                        + "</td>"
                                                                                        +
                                                                                        "<td>"
                                                                                        + requestSupCompniesInfo.initSupCompaniesData.data.charging[i].count
                                                                                        + "</td>"
                                                                                        +
                                                                                        "<td>"
                                                                                        + parseFloat(
                    requestSupCompniesInfo.initSupCompaniesData.data.charging[i].unitPrice).toFixed(
                    2)
                                                                                        + "</td>"
                                                                                        +
                                                                                        "<td class=\"details-fee-total\">"
                                                                                        + parseFloat(
                    requestSupCompniesInfo.initSupCompaniesData.data.charging[i].totalPrice)
                                                                                            .toFixed(
                                                                                                2)
                                                                                        + "</td>"
                                                                                        +
                                                                                        "</tr>");

        }
        var computedTotal = 0;
        $(".details-info-container").find(".details-fee-total").each(function (i,
                                                                               n) {
            computedTotal += parseFloat($(this).text());

        });
        if (computedTotal < 0) {
            computedTotal = 0;
        }
        $(".details-info-container").find(".all-total").text(computedTotal.toFixed(2)
                                                             + "RMB");
    } else {
        $(".details-info-fee").remove();
        $(".extract-tips").before("<div class='nothing-price'>暂无报价</div>");
    }
}

/**
 * 获取报关供应商信息
 */
var temp = false;

function getCompanyInfo() {
    if (temp) {
        $("#company_info").html("");
        temp = false;
    } else {
        var companyId = $("input[name='supCompany.id']").val();
        if (companyId) {
            $.ajax({
                       "url": "/base/company-findEntityById",
                       "data": {"companyId": companyId},
                       "type": "post",
                       "success": function (data) {
                           var info = "海关注册代码：" + data.com_customs_code + "&nbsp;&nbsp;";
                           info += "联系人：" + data.contactor + "&nbsp;&nbsp;";
                           info += "电话：" + data.phone + "&nbsp;&nbsp;";
                           info += "手机：" + data.mobile + "&nbsp;&nbsp;";
                           $("#company_info").html(info);
                           temp = true;
                       }
                   });
        }
    }
}

/**
 * 请求报关行报价
 */
var requestSupCompniesInfo = {
    _init: function () {
        this.chargingObj = {};
        this.chargingObj.supComId = $("input[name='supCompany.id']").val();
        this.chargingObj.iePortCode = $("input[name=export_port_code]").val();
        this.chargingObj.declaPortCode = $("input[name=declaration_port_code]").val();
        this.chargingObj.contaCount =
            (!$("input[name=container_num]").val()) ? 0 : $("input[name=container_num]").val();
        this.chargingObj.goodsCount =
            (!$("input[name=goods_item_num]").val()) ? 0 : $("input[name=goods_item_num]").val();
        this.chargingObj.transitType = $("input[name=direct_transit_code]").val();
        this.chargingObj.ieType = $("input[name=declaration_type]").val();
        this.chargingObj.isCCI = $("#isTongguanYth").val();
        this.chargingObj.supComName = $("input[name='companyIdShowName']").val();
        if (this._isValidParams) {
            this._load();
        } else {
            console.log("参数不完整");
        }
    },
    _load: function () {
        var _this = this;
        $.ajax({
                   url: '/fund/charging/query',
                   type: 'post',
                   data: JSON.stringify(_this.chargingObj),
                   contentType: 'application/json',
                   dataType: 'json',
                   success: function (data) {
                       console.log(data);
                       if (data.result) {
                           _this.initSupCompaniesData = data;
                           var text = " ";
                           var offer = data.data;
                           var offerDeclarationAmount = 0;
                           var hasQuote = false;
                           for (var i = 0; i < offer.charging.length; i++) {
                               offerDeclarationAmount +=
                                   parseFloat(offer.charging[i].totalPrice);
                               if (offerDeclarationAmount) {
                                   hasQuote = true;
                               }
                           }
                           if (offerDeclarationAmount < 0) {
                               offerDeclarationAmount = 0;
                           }
                           if ($.fn.order.isExport) {
                               if (hasQuote) {
                                   text = "报关费：" + offerDeclarationAmount.toFixed(2) + "元";
                               } else {
                                   text = "该报关行暂无报价;";
                               }
                           } else {
                               if (hasQuote) {
                                   text = "报关费：" + offerDeclarationAmount.toFixed(2) + "元";
                               } else {
                                   text = "该报关行暂无报价;";
                               }
                           }
                           text +=
                               "<button style='float: right;' name='详细说明' onclick='javascript:getDetailsInfo();'>详细说明</button>";
                           $("#supCompany_quotPrice").html(text);
                       } else {
                           console.log(data.msg);
                       }

                   },
                   error: function () {
                       $("#supCompany_quotPrice").html("没有查到当前报关行的报价信息！");
                   }
               });
    },
    _isValidParams: function () {
        var isValidCount = 0;
        var propLen = 0;
        for (var prop in this.chargingObj) {
            this.propLen++;
            if (this.chargingObj[prop] || this.chargingObj[prop] == 0) {
                isValidCount++;
            }
        }
        if (propLen == isValidCount) {
            return true;
        }
    }
};
/**
 * 初始化需要使用到的函数
 * @constructor
 */
var InitFunctions = {
        initSupCompaniesData: '',
        initSupCompanies: function () {
            var port_code_val_input = $("input[name='declaration_port_code']");
            var port_code = port_code_val_input.val();
            if (port_code == "" || port_code == undefined) {
                return;
            }
            var isExport = $.fn.order.isExport;
            var module_id = $($("input[name='supCompany.id']").parent("div.dropdown")).dropdown(
                "get").id();
            var module = $.fn.dropdown.find(module_id); //得到报关行的下拉框组件对象
            /**
             * 获取关联码头数据的报关行数据
             */
            $.ajaxPlugin({
                             url: $.fn.api.settings.api.supCompany,
                             data: {code: port_code, isExport: isExport},
                             dataType: 'json',
                             type: 'post',
                             success: function (data) {
                                 var results = data.results;
                                 var filteredSupCompany = [];
                                 $.data.supComData = results;
                                 /**
                                  * 构造下拉框菜单
                                  */
                                 $.each(results, function (i, n) {
                                     filteredSupCompany.push(
                                         {
                                             name: n.name,
                                             value: n.value,
                                             text: n.name
                                         });
                                 });
                                 module.setup.menu({values: filteredSupCompany});
                             }
                         })
            ;
        },
        getSupCompanyOffer: function (declaration_company_id) {
            var _this = this;
            if (declaration_company_id == "" || declaration_company_id == undefined) {
                return;
            }
            requestSupCompniesInfo._init();
            /*var chargingObj = {};
             chargingObj.supComId = $("input[name='supCompany.id']").val();
             chargingObj.iePortCode = $("input[name=export_port_code]").val();
             chargingObj.declaPortCode = $("input[name=declaration_port_code]").val();
             chargingObj.contaCount =
             (!$("input[name=container_num]").val()) ? 0 : $("input[name=container_num]").val();
             chargingObj.goodsCount =
             (!$("input[name=goods_item_num]").val()) ? 0 : $("input[name=goods_item_num]").val();
             chargingObj.transitType = $("input[name=direct_transit_code]").val();
             chargingObj.ieType = $("input[name=declaration_type]").val();
             chargingObj.isCCI = $("#isTongguanYth").val();
             $.ajax({
             url: '/fund/charging/query',
             type: 'post',
             data: JSON.stringify(chargingObj),
             contentType: 'application/json',
             dataType: 'json',
             success: function (data) {
             console.log(data);
             if (data.result) {
             _this.initSupCompaniesData = data;
             var text = " ";
             var offer = data.data;
             var offerDeclarationAmount = 0;
             var hasQuote = false;
             for (var i = 0; i < offer.charging.length; i++) {
             offerDeclarationAmount +=
             parseFloat(offer.charging[i].totalPrice);
             if (offerDeclarationAmount) {
             hasQuote = true;
             }
             }
             if (offerDeclarationAmount < 0) {
             offerDeclarationAmount = 0;
             }
             if ($.fn.order.isExport) {
             if (hasQuote) {
             text = "报关费：" + offerDeclarationAmount.toFixed(2) + "元";
             } else {
             text = "该报关行暂无报价;";
             }
             } else {
             if (hasQuote) {
             text = "报关费：" + offerDeclarationAmount.toFixed(2) + "元";
             } else {
             text = "该报关行暂无报价;";
             }
             }
             text +=
             "<button style='float: right;' name='详细说明' onclick='javascript:getDetailsInfo();'>详细说明</button>";
             $("#supCompany_quotPrice").html(text);
             } else {
             console.log(data.msg);
             }

             },
             error: function () {
             $("#supCompany_quotPrice").html("没有查到当前报关行的报价信息！");
             }
             });*/
        },
        showFetchContainerBtn: function () {
            $.data.lastPortCode = $("input[name='declaration_port_code']").val();
            if ("5189" == $.data.lastPortCode) {
                $("button#fetchBtn").show();
            }
        },
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            return null;
        },
        containerOperations: function () {
            this.sortContainers();
            this.scrollContainerBody();
            this.collectContainerInfo();
        },
        sortContainers: function () {
            var __containerTable = $containersTable;
            if ($containersTable.length == 0) {
                __containerTable = $("table[name='containerTable']");
            }
            var containerTrs = __containerTable.find("tbody tr");
            var cArray = new Array();
            for (var i = 0; i < containerTrs.length; i++) {
                var $tr = $(containerTrs[i]);
                cArray.push($tr);
            }
            cArray.sort(function (tr1, tr2) {
                var cn1 = tr1.find("td:first").text();
                var cn2 = tr2.find("td:first").text();
                var s1 = cn1.length;
                var s2 = cn2.length;
                var len = s1 > s2 ? s1 : s2;
                for (var i = 0; i < len; i++) {
                    var c1 = cn1.charCodeAt(i);
                    var c2 = cn2.charCodeAt(i);
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                }
                return 0;
            });
            var tbody = $containersTable.find("tbody");
            tbody.html('');
            $.each(cArray, function (i, n) {
                /*$.each(n.find("input:hidden"), function (j, m) {*/
                $.each(n.find("input[type=hidden]"), function (j, m) {
                    var $cinput = $(m);
                    var cname = $cinput.attr('name');
                    var reName = cname.replace(/\[\d*\]/, "[" + i + "]");
                    $cinput.attr('name', reName);
                });
                var btns = n.find("button");
                if (btns.length > 0) {
                    $(btns[0]).on('click', updateBtnClick);
                    $(btns[1]).on('click', deleteBtnClick);
                }
                tbody.append(n);
            });
        },
        scrollContainerBody: function () {
            var __containerTable = $containersTable;
            var isReadMode = false;
            if ($containersTable.length == 0) {
                __containerTable = $("table[name='containerTable']");
                isReadMode = true;
            }
            var $thead = __containerTable.find('thead');
            var $theadTds = $thead.find('tr:first th');
            var tableWidth = __containerTable.width();
            var $tbody = __containerTable.find('tbody');
            var $tbodyTrs = $tbody.find('tr');
            var setTheadScrollStyle = function () {
                var tbr0 = $($tbodyTrs[0]);
                $thead.attr('style', "display:block;width:" + tableWidth + "px");

                $($theadTds[0]).width(tbr0.find("td:eq(0)").width() + 1);
                $($theadTds[1]).width(tbr0.find("td:eq(1)").width());
                $($theadTds[2]).width(tbr0.find("td:eq(2)").width());
                if (!isReadMode) {
                    $($theadTds[3]).width(tbr0.find("td:eq(3)").width());
                }
            };
            var setTbodyScrollStyle = function () {
                var w1 = 0.25 * tableWidth, w2 = 0.25 * tableWidth,
                    w3 = 0.1 * tableWidth, w4 = 0.4 * tableWidth;
                if (isReadMode) {
                    w1 = 0.4 * tableWidth;
                    w2 = 0.4 * tableWidth;
                    w3 = 0.2 * tableWidth;
                }
                $tbody.attr('style',
                    "display:block;overflow:auto;height:300px;width:" + tableWidth + "px");
                $tbodyTrs.each(function (i, n) {
                    var $tr = $(n);
                    var $tds = $tr.find('td');
                    $($tds[0]).width(w1);
                    $($tds[1]).width(w2);
                    $($tds[2]).width(w3);
                    if (!isReadMode) {
                        $($tds[3]).width(w4 - 20);
                    }
                })
            };
            var clearTheadScrollStyle = function () {
                $thead.attr('style', "");
                $($theadTds[0]).attr('style', "");
                $($theadTds[1]).attr('style', "");
                $($theadTds[2]).attr('style', "");
                $($theadTds[3]).attr('style', "");
            };
            var clearTbodyScrollStyle = function () {
                $tbody.attr('style', "");
                $tbodyTrs.each(function (i, n) {
                    var $tr = $(n);
                    var $tds = $tr.find('td');
                    $($tds[0]).attr('style', "");
                    $($tds[1]).attr('s'
                                    + 'tyle', "");
                    $($tds[2]).attr('style', "");
                    $($tds[3]).attr('style', "");
                })
            };
            if ($tbodyTrs.length > 9) {
                setTbodyScrollStyle();
                setTheadScrollStyle();
            } else {
                clearTheadScrollStyle();
                clearTbodyScrollStyle();
            }
        },
        collectContainerInfo: function () {
            var __containerTable = $containersTable;
            if ($containersTable.length == 0) {
                __containerTable = $("table[name='containerTable']");
            }
            var $tbody = __containerTable.find('tbody');
            var $tbodyTrs = $tbody.find('tr');
            var containerCount = $tbodyTrs.length;
            var sizeCollector = {"20GP": 0, "40GP": 0};
            $.each($tbodyTrs, function (i, n) {
                var sizeShow = $('td:eq(1)', $(n)).text();
                var size = sizeShow.indexOf("20") > 0 ? "20GP" : "40GP";
                var count = sizeCollector[size];
                sizeCollector[size] = count + 1;
            });
            var countText = "总计：" + containerCount + "个柜"
                            + "&nbsp;&nbsp;[ 20尺: " + sizeCollector["20GP"] + " ]"
                            + "&nbsp;&nbsp;[ 40尺: " + sizeCollector["40GP"] + " ]";
            $("#containerListSummary label").html(countText);
            if (containerCount > 0) {
                $("#containerListSummary").show();
            } else {
                $("#containerListSummary").hide();
            }
        },
        scrollCommodityBody: function () {

            var __goodsTable = $goodsTable;
            var isReadMode = false;
            if ($containersTable.length == 0) {
                __goodsTable = $("table#goodsListTable");
                isReadMode = true;
            }
            var $thead = __goodsTable.find('thead');
            var $theadTds = $thead.find('tr:first th');
            var tableWidth = __goodsTable.width();
            var $tbody = __goodsTable.find('tbody');
            var $tbodyTrs = $tbody.find('tr');
            var clearTheadScrollStyle = function () {
                $thead.attr('style', "");
                $.each($theadTds, function (i, n) {
                    $(n).attr('style', "");
                });
            };
            var clearTbodyScrollStyle = function () {
                $tbody.attr('style', "");
                $tbodyTrs.each(function (i, n) {
                    var $tr = $(n);
                    var $tds = $tr.find('td');
                    $.each($tds, function (i, n) {
                        $(n).attr('style', "");
                    });
                })
            };
            clearTheadScrollStyle();
            clearTbodyScrollStyle();

            var widthArray = [];
            var setTheadScrollStyle = function () {
                var tbr0 = $($tbodyTrs[0]);
                var tdLength = $theadTds.length;
                for (var i = 0; i <= tdLength; i++) {
                    widthArray.push(tbr0.find("td:eq(" + i + ")").width());
                    $($theadTds[i]).width(widthArray[i]);
                }
                $thead.attr('style', "display:block;width:" + tableWidth + "px");
            };
            var setTbodyScrollStyle = function () {
                $tbody.attr('style',
                    "display:block;overflow:auto;height:340px;width:" + tableWidth + "px");
                $tbodyTrs.each(function (i, n) {
                    var $tr = $(n);
                    var $tds = $tr.find('td');
                    $.each($tds, function (i, n) {
                        $(n).width(widthArray[i]);
                    });
                    if (!isReadMode) {
                        $($tds[$tds.length - 1]).width(widthArray[$tds.length - 1] - 20);
                    }
                })
            };
            if ($tbodyTrs.length > 10) {
                setTheadScrollStyle();
                setTbodyScrollStyle();
            }
        },
        markRemarkInitComplete:function(){
            var rk = $("input[name='remark']");
            // var combineRk = combineRemark();
            // if(combineRk !== rk.val() && $("input[name='actionChain']").val() !== 'C3'){
            //     rk.attr("stopAutoComp", "stopAutoComp");
            // }
            rk.attr("init", "done");
        },
        initRemarkInputFocusAction:function(){
            $("input[name='remark']").bind('focus', function (event) {
                var rk, rkVal, stopAutoComp;
                rk = $(event.target);
                stopAutoComp = rk.attr("stopAutoComp");
                if(stopAutoComp){
                    return;
                }
                rkVal = rk.val();
                rk.attr("preval", rkVal);
            }).bind('blur', function(event){
                var rk, rkVal, preval, stopAutoComp;
                rk = $(event.target);
                stopAutoComp = rk.attr("stopAutoComp");
                if(stopAutoComp){
                    return;
                }
                rkVal = rk.val();
                preval = rk.attr("preval");
                if(rkVal.trim() !== preval.trim()){
                    rk.attr("stopAutoComp", "stopAutoComp");
                }
            });

        }
    }
;

/*添加额外提示*/
function addShowErrors(arg) {
    if ($(".errorMsgContainer").css("display")
        == "block") {
        $(".modal-body").append('<li class="errorList">' + arg + ' </li>');
    } else {
        $(".errorMsgContainer").show();
        $(".error.message").show();
        $(".modal-body").append('<li class="errorList">' + arg + ' </li>');
        $(".closeError").click(function () {
            $(".errorMsgContainer").hide();
            $(".error.message").hide();
            $(".modal-body").text("");
        });
    }
}

$(document).ready(function () {
    layout();//新版页面加入这个函数
    isVisibility();
    var reg = /^[0-9]{1,}\.[0-9]{1,}/;
    var $totalPrice = $("#total_price");
    var $unitPrice = $("#unit_price");
    var $count = $("#count");
    var $unitCode = $("#unitCode");
    var $legalUnitCode = $("#legalUnitCode");
    var $legalCount = $("#legal_count");
    var $secondUnitCode = $("#secondUnitCode");
    var $secondCount = $("#second_count");
    var $goodsNetWeight = $("#goods_net_weight");
    var $goodsGrossWeight = $("#goods_gross_weight");
    var $other_goods_addr = $("input[name='other_goods_addr']");
    var $netWeight = $("input[name = 'net_weight']");
    var $grossWeight = $("input[name = 'gross_weight']");
    var $totalNetWeight = $(".total-net-weight");

    /*当净重不满足条件亮红框时，修改后失去焦点重新验证提示显示*/
    /*$netWeight.blur(function () {
     if ($netWeight.parent().hasClass("error")) {
     var netWeightVal = parseInt($netWeight.val());
     var grossWeightVal = parseInt($grossWeight.val());
     var totalNetWeightVal = parseInt($totalNetWeight.val());
     if (!netWeightVal) {
     addShowErrors("净重为必填项");
     return;
     }
     if (!(netWeightVal <= grossWeightVal)) {
     addShowErrors("净重要小于毛重");
     return;
     }
     if ($.fn.order.isExport) {
     if (!(netWeightVal == totalNetWeightVal)) {
     addShowErrors("总净重要等于净重总汇");
     return;
     }
     }

     }
     });*/
    /*当主体信息中毛重小于净重时，净重亮红框，修改了毛重，去掉净重的红框*/
    $grossWeight.blur(function () {
        if ($netWeight.val() && $netWeight.val() != " "
            && $netWeight.parent().hasClass("error")) {
            var validateArr = ["gross_weight", "net_weight"];
            relateValidate("allform", validateArr);
        }
    });

    //其他货源地失去焦点时填到备注中
    $other_goods_addr.blur(function () {
        addRemark(detailsPack);
    });
    $totalPrice.keypress(function (e) {
        var v = Number($(this).val() + String.fromCharCode(e.keyCode));
        var c = Number($count.val());
        if (c) {
            $unitPrice.val((v / c).toFixed(4));
            /*if ($("#commodities").find(".error").length) {
             $('.ui.goodsForm').form('is valid');
             }*/

        }
    });
    $totalPrice.keyup(function (e) {
        if (e.keyCode == 8) {
            var v = Number($(this).val());
            var c = Number($count.val());
            if (c) {
                $unitPrice.val((v / c).toFixed(4));
            }
        }

    });
    $totalPrice.blur(function () {
        var v = Number($(this).val());
        var c = Number($count.val());
        if (c) {
            $unitPrice.val((v / c).toFixed(4));
        }
    });
    //todo 会退键删除数字的时候有bug，不会触发事件
    $count.keypress(function (e) {
        var v = Number($totalPrice.val());
        var c = Number($(this).val() + String.fromCharCode(e.keyCode));
        if (c) {
            $unitPrice.val((v / c).toFixed(4));
            /*if ($("#commodities").find(".error").length) {
             $('.ui.goodsForm').form('is valid');
             }*/
        }
    });
    $count.keyup(function (e) {
        if (e.keyCode == 8) {
            var v = Number($totalPrice.val());
            var c = Number($(this).val());
            if (c) {
                $unitPrice.val((v / c).toFixed(4));
            }
        }

    });
    //净重改变时，计价数量、法定数量也自动改变
    $goodsNetWeight.blur(function () {
        if ($unitCode.val() == "035") {
            $count.val($goodsNetWeight.val());
            $legalCount.val($goodsNetWeight.val());
            var v = Number($totalPrice.val());
            var c = Number($count.val());
            if (c) {
                $unitPrice.val((v / c).toFixed(4));
            }
        }
    });

    //同步计价数量、法定数量及第二单位
    $count.blur(function () {
        if (!$(this).val()) {
            return;
        }
        var v = Number($totalPrice.val());
        var c = Number($(this).val());
        if (c) {
            $unitPrice.val((v / c).toFixed(4));
        }
        if ($unitCode.val() === $legalUnitCode.val()) {
            $legalCount.val($count.val());
        }
        if ($unitCode.val() === $secondUnitCode.val()) {
            $secondCount.val($count.val());
        }
        if ($unitCode.val() == "035") {
            $goodsNetWeight.val($count.val());
        }
        if ($("#legal_count").parent().hasClass("error")) {
            var validateArr;
            if ($.fn.order.isExport) {
                validateArr = ["#legal_count", "#goods_net_weight", "#unit_price"];
            } else {
                validateArr = ["#legal_count", "#unit_price"];
            }
            relateValidate("commodities", validateArr);
        } else if ($("#goods_net_weight").parent().hasClass("error")) {
            var validateArr;
            if ($.fn.order.isExport) {
                validateArr = ["#legal_count", "#goods_net_weight", "#unit_price"];
            } else {
                validateArr = ["#legal_count", "#unit_price"];
            }
            relateValidate("commodities", validateArr);
        }
    });
    $unitCode.change(function () {
        if ($unitCode.val() === $secondUnitCode.val()) {
            $secondCount.val($count.val());
        }
    });
    //同步法定单位与第二单位
    $legalCount.change(function () {
        if ($legalUnitCode.val() === $secondUnitCode.val()) {
            $secondCount.val($legalCount.val());
        }
        if ($legalUnitCode.val() == "035") {
            $goodsNetWeight.val($legalCount.val());
        }
    });
    $secondCount.change(function () {
        if ($secondUnitCode.val() == '035') {
            $goodsNetWeight.val($secondCount.val());
        }
    });
    /*出口加工贸易当备案号符合B, C, E开头后加11位数字时设置相应监管方式和征免性质*/
    if ($.fn.order.isExport) {
        if ($.fn.order.isProcessTrade) {
            $("input[name='record_id']").blur(function () {
                var regOne = /^B[0-9]{11}$/;
                var regTwo = /^C[0-9]{11}$/;
                var regThree = /^E[0-9]{11}$/;
                var val = $(this).val();
                if (val) {
                    if (regOne.test(val)) {
                        $("input[name='trade_mode_code']").parent().dropdown("set selected",
                                                                             "0214");
                        $("input[name='levymode_code']").parent().dropdown("set selected", "502");
                    } else if (regTwo.test(val)) {
                        $("input[name='trade_mode_code']").parent().dropdown("set selected",
                                                                             "0615");
                        $("input[name='levymode_code']").parent().dropdown("set selected", "503");
                    } else if (regThree.test(val)) {
                        $("input[name='trade_mode_code']").parent().dropdown("set selected", "");
                        $("input[name='levymode_code']").parent().dropdown("set selected", "");
                        $("input[name='trade_mode_code']").parent().dropdown("set text", "");
                        $("input[name='levymode_code']").parent().dropdown("set text", "");
                        $("input[name='trade_mode_code']").val("");
                        $("input[name='levymode_code']").val("");
                    }
                    isVisibility();
                    needAddProcessFee();
                    if ($(".ui.allform").find(".error").length) {
                        $(".ui.allform").form("is valid");
                    }
                }
            });
        }
    }
    /*合同协议号和发票号联动*/
    if ($.fn.order.isExport) {
        $("input[name='contract_no']").blur(function () {
            var contractNo = $(this).val();
            if (contractNo) {
                $("input[name='invoice_no']").val(contractNo);
            }
            if ($("input[name='invoice_no']").parent().hasClass("error")) {
                var validateArr = ["contract_no", "invoice_no"];
                relateValidate("allform", validateArr);
            }
        });
    }
    /*当商品信息中毛重小于净重时，净重亮红框，修改了毛重，去掉净重的红框*/
    $goodsGrossWeight.blur(function () {
        if ($.fn.order.isExport) {
            if ($goodsNetWeight.val() && $goodsNetWeight.val() != " "
                && $goodsNetWeight.parent().hasClass("error")) {
                var validateArr = ["#goods_gross_weight", "#goods_net_weight"];
                relateValidate("commodities", validateArr);
            }
        }
    });

    /*进口一般贸易要素规格型号点击时请求要素弹出框的数据*/
    if (!$.fn.order.isExport) {
        if (!$.fn.order.isProcessTrade) {
            $("#goods_mode").click(function () {
                var response;
                var codeNum = $("#code_t").val();
                // var name = $("#code_t").next("input[type='hidden']").val();
                var code_s = $("#code_s").val();
                if (codeNum) {
                    $.ajaxPlugin({
                                     url: $.fn.api.settings.api.goodsCode.replace(/key={query}/,
                                                                                  ''),
                                     data: {
                                         key: codeNum,
                                         v: Math.random()
                                     },
                                     type: 'get',
                                     dataType: 'json',
                                     success: function (data) {
                                         var results = data.results;
                                         for (var i = 0; i < results.length; i++) {
                                             if (results[i].data.code_s == code_s) {
                                                 response =
                                                     results[i].data.good_mode;
                                                 break;
                                             }
                                         }
                                         loadLabel(response,
                                                   $("#goods_mode").val());
                                     },
                                     error: function () {

                                     }
                                 });
                }
            });
        }
    } else {
        if (!$.fn.order.isProcessTrade) {
            $("#goods_mode").click(function () {
                var response;
                var codeNum = $("#code_t").val();
                // var name = $("#code_t").next("input[type='hidden']").val();
                var code_s = $("#code_s").val();
                if (codeNum) {
                    $.ajaxPlugin({
                                     url: $.fn.api.settings.api.goodsCode.replace(/key={query}/,
                                                                                  ''),
                                     data: {
                                         key: codeNum,
                                         v: Math.random()
                                     },
                                     type: 'get',
                                     dataType: 'json',
                                     success: function (data) {
                                         var results = data.results;
                                         for (var i = 0; i < results.length; i++) {
                                             if (results[i].data.code_s == code_s) {
                                                 response =
                                                     results[i].data.good_mode;
                                                 break;
                                             }
                                         }
                                         loadLabel(response,
                                                   $("#goods_mode").val());
                                     }
                                 });
                }
            });
        }
    }
    /*$('#declaration_tabs .item').tab(
     {
     onLoad: function (tabPath, parameterArray, historyEvent) {
     var $ifames = $(this).find("iframe");
     if ($ifames.length == 0) {
     return;
     }
     var i = $ifames[0];
     var height = i.contentWindow.document.body.scrollHeight;
     $(this).height(height);

     }
     });*/

    /*表单验证扩展方法*/
    /*验证输入框的值是否小于某个输入框的值 根据input的name或者id*/
    $.fn.form.settings.rules.lessThan = function (arg1, arg2) {
        var compareValue = $('input[name=' + arg2 + ']').val() ? parseInt(
            $('input[name=' + arg2 + ']').val()) : parseInt($("#" + arg2).val());
        if (compareValue) {
            return (parseInt(arg1) <= compareValue);
        } else {
            return true;
        }
    };
    /*验证输入框的值是否大于某个输入框的值 根据input的name或者id*/
    $.fn.form.settings.rules.greaterThan = function (arg1, arg2) {
        var compareValue = $('input[name=' + arg2 + ']').val() ? parseInt(
            $('input[name=' + arg2 + ']').val()) : parseInt($("#" + arg2).val());
        if (compareValue) {
            return (parseInt(arg1) >= compareValue);
        } else {
            return true;
        }
    };

    $.fn.form.settings.rules.maxValue = function (arg) {
        var compareVal = 999999999;
        return parseFloat(arg) > 0 && parseFloat(arg) <= compareVal;
    };
    /*验证表头总净重与表体总净重是否相等*/
    $.fn.form.settings.rules.equal = function (arg1, arg2) {
        if ($.fn.order.isExport) {
            if ($("." + arg2)) {
                var compareValue = parseInt($("." + arg2
                ).text());
                return (parseInt(arg1) == compareValue);
            }
        } else {
            return true;
        }
    };

    var allInputs__ = $("input:text");
    $.data.inputsLength = allInputs__.length;
    $.each(allInputs__, function (i, n) {
        $(n).attr('jumpIndex', i);
    });

    //通过回车跳到下一个输入框
    $("body input:text").on('keyup', function (event) {
        if (event.keyCode == 13) {
            /*var $eventTargetObj = $(event.target);
             setTimeout(function () {*/
            $(event.target).declarationJump();
            /* }, 300);*/

        }
    });

    /**
     * 暂时使用“使用模板”按钮判断是否是编辑页面
     */
    if ($("#useTemplateBtn").length > 0) {
        //显示获取柜号的按钮
        InitFunctions.showFetchContainerBtn();
        //加载可用的报关行
        InitFunctions.initSupCompanies();
        //加载报关行的报关费
        InitFunctions.getSupCompanyOffer($("input[name='supCompany.id']").val());
    }

    $("#declaration_tabs .item").click(function () {
        var index = $(this).index();
        var $currentTab = $(".tab").eq(index);
        $(this).addClass("active").siblings().removeClass("active");
        $currentTab.show().siblings(".tab").hide();
        var height = $currentTab.find("iframe").contents().height();
        $currentTab.find("iframe").css("height", height + "px");

    });
    //柜号排序 柜量统计和高度调整
    InitFunctions.containerOperations();
    //商品列表高度调整
    InitFunctions.scrollCommodityBody();
    //标记备注栏已经完成初始化
    InitFunctions.markRemarkInitComplete();
    //初始化备注栏事件
    // InitFunctions.initRemarkInputFocusAction();
})
;
